package util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;

public class CommonUtils {
    private CommonUtils() {
    }

    public static JSONObject crawl(String url, String charsetName) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
        CloseableHttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStreamReader reader = new InputStreamReader(entity.getContent(), charsetName);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String input;
        while ((input = bufferedReader.readLine()) != null) {
            return JSONObject.parseObject(input.substring(8, input.lastIndexOf(")")));
        }
        return new JSONObject();
    }

    /**
     * 在控制台打印错误信息，并输出错误信息到文件
     *
     * @param message
     * @throws IOException
     */
    public static void logError(String message) throws IOException {
        System.err.println(message);
        FileUtils.writeStringToFile(new File("error.log"), LocalDateTime.now() + "\t" + message + "\n", Charsets.UTF_8, true);
    }
}
